<?php

defined('IN_XLP') or exit('Access Denied');

class weixinModel extends Model {

	private $_wx = null;  //微信类对象
	private $_wx_param = array(); //微信5个基本参数
	private $_notifyURL = 'http://wx.51jhome.com/index.php?g=shop&c=notify';

	function __construct() {
		parent::__construct();
		$this->_init();
	}

	private function _init() {
		T('weixin/weixin.pay');

		//缓存中获取5个微信参数
		$this->_wx_param = F('weixin/setting');
		$this->_wx_param = $this->_wx_param['user_info'];

		if (!($this->_wx_param['wx_AppId'] && $this->_wx_param['wx_AppSecret'])) {
			$this->errorLog('缺少微信相关参数');
		}

		$this->_wx = new weixinPay($this->_wx_param);
	}

	/*
	 * 处理错误消息
	 */
	private function errorLog($msg = '') {
		saveLog('weixin_model/error', $msg);
		showError($msg);
	}

	public function setNotifyURL($url) {
		$this->_notifyURL = $url;
	}

	public function getNotifyURL() {
		return $this->_notifyURL;
	}

	/*
	 * 获取基础支持access_token
	 */
	public function getBaseAccessToken() {
		//读取缓存
		$base_token = S('token/weixin/access_token_' . $this->_wx_param['wx_AppId']);

		if ($base_token) {
			return $base_token;
		} else {
			try {
				$param_arr = $this->_wx->fetchBaseAccessToken();
			} catch (WechatException $e) {
				showError($e->getMsg());
			}
			//缓存token
			S('token/weixin/access_token_' . $this->_wx_param['wx_AppId'], $param_arr['base_token'], $param_arr['base_token_expires_in']);
			return $param_arr['base_token'];
		}
	}


	/*
	 * 生成支付参数
	 */

	public function getWeixinPayParam($body, $total_fee, $out_sn, $others=null) {

		//去除订单名称空白字符
		$body = preg_replace('/\s/', '', $body);
		//商品描述最多128字节
		if(strlen($body) > 128) {
			$body = cnsubStr($body, 40);
		}

		$temp = array();
		$temp['body']         = $body;
		$temp['out_trade_no'] = $out_sn;
		$temp['total_fee']    = $total_fee * 100;	//注意单位为分

		//其它参数
		if(is_array($others)) {
			$temp = array_merge($temp, $others);
		}

		try {
			//设置微信支付通知URL
			$this->_wx->setNotifyURL($this->_notifyURL);
			//生成微信支付参数数组
			$wx_pay_param = $this->_wx->genPayParams($temp);
		} catch (WechatException $e) {
			$this->errorLog($e->getMsg());
		}

		return $wx_pay_param;
	}

	/*
	 * 验证微信支付通知
	 */

	public function checkWeixinNotify() {

		try {
			//签名验证类
			$sign = new Sign();
			//删除微信支付通知地址中多余的get参数
			unset($_GET['g']);
			unset($_GET['c']);
			unset($_GET['m']);
			//检查GET参数
			$is_get_valid = $sign->checkNotifySign($this->_wx_param['wx_PartnerKey']);
			//检查POST参数
			$is_post_valid = $sign->checkNotifyPost($this->_wx_param['wx_AppId'], $this->_wx_param['wx_PaySignKey']);
		} catch (WechatException $e) {
			$this->errorLog($e->getMsg());
		}

		if ($is_get_valid && $is_post_valid) {
			return true;
		} else {
			return false;
		}
	}

	/*
	 * 微信发货通知
	 */

	public function delivery($openid, $out_sn, $transid, $deliver_msg = "ok") {
		$base_token = $this->getBaseAccessToken();
		//发送通知
		$result = $this->_wx->delivery($base_token, $openid, $out_sn, $transid, $deliver_msg);

		return $result;
	}

	/**
	 * 向用户发送微信模板消息
	 * @param  Array  $info 订单信息，包括买家openid，订单号，订单总金额，商品名称，商品数量
	 * @param  String $tpl		模板id
	 * @param  String $url		消息链接
	 * @param  String $remark	 消息备注
	 */
	public function sendMsg($info, $tpl, $url, $remark = '') {
		$setting = F('weixin/setting');
		if (isHave($setting['user_info']['wx_AppId']) && isHave($setting['user_info']['wx_AppSecret'])) {
			T('weixin/weixin.api');
			$weixinMsgApi = new weixinMsgApi(array(
				'appid' => $setting['user_info']['wx_AppId'],
				'appsecret' => $setting['user_info']['wx_AppSecret']
			));
		}

		switch ($tpl) {
			case '6DkXtO_0TjGmaELJ-7-NkbmJzZeJhLk0IRkHdyftUMI':
				$sendInfo = array(
					'touser' => $info['openid'],
					'template_id' => $tpl,
					'url' => $url,
					'topcolor' => '#E1E6B3',
					'data' => array(
						'first' => array('value' => "您收到一条出借申请", 'color' => '#173177'),
						'keyword1' => array('value' => outTime(TIME,2), 'color' => '#173177'),
						'keyword2' => array('value' => "{$info['amount']}元", 'color' => '#173177'),
						'remark' => array('value' => "申请人:{$info['username']} 若有疑问请联系：0510-88737110", 'color' => '#173177')
					)
				);
				break;
			case 'DOBy8fgsMZFLo0sF-vnpZeOEXefZxg5W2KaRgmLIfpI':
				$sendInfo = array(
					'touser' => $info['openid'],
					'template_id' => $tpl,
					'url' => $url,
					'topcolor' => '#E1E6B3',
					'data' => array(
						'first' => array('value' => "恭喜，你的借款已生成", 'color' => '#173177'),
						'keyword1' => array('value' => "{$info['username']}", 'color' => '#173177'),
						'keyword2' => array('value' => "{$info['amount']}元", 'color' => '#173177'),
						'keyword3' => array('value' => outTime(TIME,2), 'color' => '#173177'),
						'remark' => array('value' => "若有疑问请联系：0510-88737110", 'color' => '#173177')
					)
				);
				break;
			case 'Z3-OKHDbH19ZpxrDzw32WJ2sdZXp0o6zA1mQJifCUG4':
				$sendInfo = array(
					'touser' => $info['openid'],
					'template_id' => $tpl,
					'url' => '',
					'topcolor' => '#E1E6B3',
					'data' => array(
						'first' => array('value' => "您好，您的出借申请被拒绝", 'color' => '#173177'),
						'keyword1' => array('value' => "{$info['username']}", 'color' => '#173177'),
						'keyword2' => array('value' => "线下借贷", 'color' => '#173177'),
						'keyword3' => array('value' => "被驳回", 'color' => '#173177'),
						'keyword4' => array('value' => outTime(TIME,2), 'color' => '#173177'),
						'remark' => array('value' => "祝您生活愉快!  若有疑问请联系：0510-88737110", 'color' => '#173177')
					)
				);
				break;
			case 'VoprW-bKInXLltm6TgRWXuW7LLhgY3egJe5d5HlhwJg':
				$sendInfo = array(
					'touser' => $info['openid'],
					'template_id' => $tpl,
					'url' => $url,
					'topcolor' => '#E1E6B3',
					'data' => array(
						'first' => array('value' => "{$info['first']}", 'color' => '#173177'),
						'keyword1' => array('value' => "资信借(补借条)", 'color' => '#173177'),
						'keyword2' => array('value' => "{$info['keyword2']}", 'color' => '#173177'),
						'keyword3' => array('value' => "{$info['username']}", 'color' => '#173177'),
						'keyword4' => array('value' => "{$info['amount']} 元", 'color' => '#173177'),
						'keyword5' => array('value' => outTime(TIME,2), 'color' => '#173177'),
						'remark' => array('value' => "若有疑问请联系：0510-88737110", 'color' => '#173177')
					)
				);
				break;
			case 'kkh50k3ucF4QXbipxQ-beToabxiQGuiXOy46snEYqx0':
				$sendInfo = array(
					'touser' => $info['openid'],
					'template_id' => $tpl,
					'url' => $url,
					'topcolor' => '#E1E6B3',
					'data' => array(
						'first' => array('value' => "申请取消借款单", 'color' => '#173177'),
						'keyword1' => array('value' => "{$info['username']}", 'color' => '#173177'),
						'keyword2' => array('value' => "{$info['order_sn']}", 'color' => '#173177'),
						'keyword3' => array('value' => "申请中", 'color' => '#173177'),
						'keyword4' => array('value' => "{$info['quota']} 元", 'color' => '#173177'),
						'keyword5' => array('value' => "已成功提交到{$info['lender']}", 'color' => '#173177'),
						'remark' => array('value' => "若有疑问请联系：0510-88737110", 'color' => '#173177')
					)
				);
				break;
			case 'yUoU82b3hISt4TQHkN63CY3ZixWf9gB8J4qQG9IOJtM':
				$sendInfo = array(
					'touser' => $info['openid'],
					'template_id' => $tpl,
					'url' => $url,
					'topcolor' => '#E1E6B3',
					'data' => array(
						'first' => array('value' => "{$info['first']}", 'color' => '#173177'),
						'keyword1' => array('value' => "{$info['order_sn']}", 'color' => '#173177'),
						'keyword2' => array('value' => "{$info['keyword2']}", 'color' => '#173177'),
						'keyword3' => array('value' => outTime(TIME,2), 'color' => '#173177'),
						'remark' => array('value' => "感谢您的使用!  若有疑问请联系：0510-88737110", 'color' => '#173177')
					)
				);
				break;					
		}
		
		$res = $weixinMsgApi->sendTplMessage($sendInfo);
		if (!$res) {
			$err_msg = array('code' => $weixinMsgApi->errCode, 'msg' => $weixinMsgApi->errMsg, 'data' => $weixinMsgApi->dataInfo);
			saveLog('notice/weixin_tpl', $err_msg);
			saveLog('notice/order_info', $info);
		}
	}


	//借贷订单提醒
	public function sendOrderMsg($info, $remark = '') {
		$setting = F('weixin/setting');
		if (isHave($setting['user_info']['wx_AppId']) && isHave($setting['user_info']['wx_AppSecret'])) {
			T('weixin/weixin.api');
			$weixinMsgApi = new weixinMsgApi(array(
				'appid' => $setting['user_info']['wx_AppId'],
				'appsecret' => $setting['user_info']['wx_AppSecret']
			));
		}
		$sendInfo = array(
			'touser' => $info['openid'],
			'template_id' => "ktHOHZfVWubEE1A-rOKvPqn0L3SsB1_Dt-jvkKW_n50",
			'url' => '',
			'topcolor' => '#E1E6B3',
			'data' => array(
				'first' => array('value' => $info['first'], 'color' => '#743A3A'),
				'keyword1' => array('value' => "{$info['order_sn']}", 'color' => '#173177'),
				'keyword2' => array('value' => "{$info['name']}", 'color' => '#173177'),
				'keyword3' => array('value' => "{$info['amount']} 元", 'color' => '#FF0000'),
				// 'keyword4' => array('value' => "{$info['status']}", 'color' => '#C4C400'),
				'remark' => array('value' => $remark, 'color' => '#008000')
			)
		);
		$res = $weixinMsgApi->sendTplMessage($sendInfo);
		if (!$res) {
			$err_msg = array('code' => $weixinMsgApi->errCode, 'msg' => $weixinMsgApi->errMsg, 'data' => $weixinMsgApi->dataInfo);
			saveLog('notice/weixin_tpl', $err_msg);
			saveLog('notice/order_info', $info);
		}
	}


	//利息还款提醒
	public function sendInterestMsg($info, $remark = '') {
		$setting = F('weixin/setting');
		if (isHave($setting['user_info']['wx_AppId']) && isHave($setting['user_info']['wx_AppSecret'])) {
			T('weixin/weixin.api');
			$weixinMsgApi = new weixinMsgApi(array(
				'appid' => $setting['user_info']['wx_AppId'],
				'appsecret' => $setting['user_info']['wx_AppSecret']
			));
		}
		$sendInfo = array(
			'touser' => $info['openid'],
			'template_id' => "rQdwvHoCnd1WMLcoAWrDftnYc0WZ7K1x-Q2HTGJcIRs",
			'url' => '',
			'topcolor' => '#E1E6B3',
			'data' => array(
				'first' => array('value' => $info['first'], 'color' => '#743A3A'),
				'keyword1' => array('value' => "{$info['order_sn']}", 'color' => '#173177'),
				'keyword2' => array('value' => "{$info['number']}", 'color' => '#173177'),
				'keyword3' => array('value' => "{$info['amount']} 元", 'color' => '#173177'),
				'keyword4' => array('value' => "{$info['time']}", 'color' => '#FF0000'),
				'remark' => array('value' => $remark, 'color' => '#008000')
			)
		);
		$res = $weixinMsgApi->sendTplMessage($sendInfo);
		if (!$res) {
			$err_msg = array('code' => $weixinMsgApi->errCode, 'msg' => $weixinMsgApi->errMsg, 'data' => $weixinMsgApi->dataInfo);
			saveLog('notice/weixin_tpl', $err_msg);
			saveLog('notice/order_info', $info);
		}
	}

	/**
	 * 生成原生支付URL
	 * @param  String $out_sn 外部交易号
	 * @return String         原生支付URL
	 */
	public function getNativePayURL($out_sn) {

		try {
			$url = $this->_wx->genNativePayURL($out_sn);
		} catch (WechatException $e) {
			$this->errorLog($e->getMsg());
		}

		return $url;
	}


	/*
	 * 验证native支付回调的POST数据
	 */
	public function checkWeixinCallback() {
		try {
			//签名验证类
			$sign = new Sign();
			$out_sn = $sign->checkNativeCallback($this->_wx_param['wx_PaySignKey']);
		} catch (WechatException $e) {
			$this->errorLog($e->getMsg());
		}

		if ($out_sn !== false) {
			return $out_sn;
		} else {
			return false;
		}	
	}

	/**
	 * 原生支付 返回给微信服务器的订单信息
	 * @param  Array  $order_params 订单所必要的参数 (body,out_trade_no,total_fee)
	 * @param  Integer $retcode     订单状态代码 0表示没问题
	 * @param  String  $reterrmsg   订单信息 可用来填写UTF-8编码提示 如“商品已下架”等……
	 * @return String               XML格式的订单信息
	 */
	public function getNativePayXML($order_params, $retcode=0, $reterrmsg='OK') {
		try {
			//设置notify地址
			$this->_wx->setNotifyURL($this->_notifyURL);
			$xml = '';
			$xml = $this->_wx->genNativePayXML($order_params, $retcode, $reterrmsg);
		} catch (WechatException $e) {
			$this->errorLog($e->getMsg());	
		}

		return $xml;
	}

}
